#!/bin/bash
# scripts/deploy_to_test_server_local.sh - 使用本地文件部署到测试服务器

set -e

SERVER_IP="8.136.10.88"
SERVER_USER="root"
DEPLOY_USER="deploy"
DEPLOY_PATH="/opt/sci2"

echo "=== 开始部署到测试服务器 $SERVER_IP ==="

# 首先创建一个临时压缩包
echo "=== 创建应用压缩包 ==="
tar -czf /tmp/sci2_app.tar.gz \
  --exclude=.git \
  --exclude=log \
  --exclude=tmp \
  --exclude=node_modules \
  --exclude=vendor/bundle \
  --exclude=public/assets \
  --exclude=*.log \
  --exclude=*.sqlite3 \
  --exclude=coverage \
  --exclude=.DS_Store \
  --exclude=.idea \
  --exclude=.vscode \
  .

# 复制压缩包到服务器
echo "=== 复制应用文件到服务器 ==="
scp /tmp/sci2_app.tar.gz $SERVER_USER@$SERVER_IP:/tmp/

# 在远程服务器上执行部署命令
ssh $SERVER_USER@$SERVER_IP << 'EOF'
set -e

echo "=== 切换到部署用户 ==="
su - deploy << 'DEPLOY_SCRIPT'
set -e

echo "=== 进入部署目录 ==="
cd /opt/sci2

echo "=== 备份现有代码（如果有） ==="
if [ -d "current" ]; then
  mv current backup_$(date +%Y%m%d_%H%M%S)
fi

echo "=== 创建新的部署目录 ==="
mkdir current
cd current

echo "=== 解压应用文件 ==="
tar -xzf /tmp/sci2_app.tar.gz
rm /tmp/sci2_app.tar.gz

echo "=== 安装Ruby依赖 ==="
source /etc/profile.d/rvm.sh
bundle install --without development test --deployment --jobs 4

echo "=== 配置数据库为SQLite ==="
cat > config/database.yml << 'DATABASE_CONFIG'
production:
  adapter: sqlite3
  database: db/sci2_production.sqlite3
  pool: 5
  timeout: 5000
DATABASE_CONFIG

echo "=== 创建必要的目录 ==="
mkdir -p tmp/pids tmp/sockets log
chmod -R 755 tmp log

echo "=== 预编译资产 ==="
SECRET_KEY_BASE=$(bundle exec rails secret)
export SECRET_KEY_BASE=$SECRET_KEY_BASE
export RAILS_ENV=production
export RAILS_LOG_TO_STDOUT=true

echo "=== 创建数据库 ==="
bundle exec rails db:create
bundle exec rails db:migrate
bundle exec rails db:seed

echo "=== 预编译资产 ==="
bundle exec rails assets:precompile

echo "=== 启动服务 ==="
# 停止现有服务（如果有）
if [ -f tmp/pids/puma.pid ]; then
  kill $(cat tmp/pids/puma.pid) || true
  sleep 2
fi

# 启动Puma服务
bundle exec puma -e production -d -b tcp://0.0.0.0:3000 \
  -C config/puma.rb

echo "=== 检查服务状态 ==="
sleep 3
if [ -f tmp/pids/puma.pid ]; then
  echo "Puma服务已启动，PID: $(cat tmp/pids/puma.pid)"
else
  echo "警告: Puma服务可能未正常启动"
fi

echo "=== 部署完成 ==="
DEPLOY_SCRIPT

echo "=== 配置Nginx反向代理 ==="
cat > /etc/nginx/sites-available/sci2 << 'NGINX_CONFIG'
server {
  listen 80;
  server_name _;

  root /opt/sci2/current/public;
  try_files $uri/index.html $uri @puma;

  location @puma {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://127.0.0.1:3000;
  }

  client_max_body_size 100M;
  keepalive_timeout 10;
}
NGINX_CONFIG

echo "=== 启用Nginx配置 ==="
ln -sf /etc/nginx/sites-available/sci2 /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default

echo "=== 重启Nginx ==="
systemctl restart nginx

echo "=== 检查服务状态 ==="
systemctl status nginx --no-pager
ps aux | grep puma | grep -v grep

echo "=== 部署完成！访问地址: http://$SERVER_IP ==="
EOF

echo "=== 清理本地临时文件 ==="
rm -f /tmp/sci2_app.tar.gz

echo "=== 部署脚本执行完成 ==="